function debounce(func, wait = 166) {
  let timeout;

  function debounced(...args) {
    // eslint-disable-next-line consistent-this
    const that = this;
    const later = () => {
      func.apply(that, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  }

  debounced.clear = () => {
    clearTimeout(timeout);
  };

  return debounced;
}


$(document).ready(function () {
  $('#topic_list').on('click', '.incrementVisitCount-div', function (event) {
    var topicId = event.currentTarget.dataset.id;
    if (topicId) {
      $.post('/topic/' + topicId + '/incrementVisitCount', {}, function (data) {
        if (typeof callback === 'function') callback(data);
      });
    }
  });


  $('.j-attention').click(function () {
    const isLogin = $('.j-islogin').val();
    if (!isLogin) {
      let redirect_url = window.location.href;
      if (redirect_url && redirect_url.includes('redirect_url=')) {
        redirect_url = redirect_url.replace(/.+redirect_url=/, '');
      }
      window.location.href = '/signin?redirect_url=' + encodeURIComponent(redirect_url);
      return;
    }

    let self = this;
    let following_name = $(self).data('id');
    let api_url = self.value == '+ 订阅' ? '/user/follow' : '/user/unfollow';
    $.post(api_url, {following_name}, function (data) {
      window.Alert.show({title: data.msg}, 1000);
      if (data.status == 'success') {
        $(self).toggleClass('span-primary').toggleClass('span-info');
        self.value = self.value === '+ 订阅' ? '已订阅' : '+ 订阅';
      }
    })
  }).hover(function () {
    if (this.value === '已订阅') {
      this.value = '取消订阅'
    }
  }, function () {
    if (this.value === '取消订阅') {
      this.value = '已订阅'
    }
  });


  const windowHeight = $(window).height();
  const $backtotop = $('#backtotop');
  const top = windowHeight - $backtotop.height() - 200;


  $('body').on('keyup', function (event) {
    var $modal = $('.modal');
    if (event.keyCode === 27 && $modal.length) {
      if ($modal.length) {
        $modal.modal('hide');
        $("body").attr('style', '');
      }
    }
  });

  function moveBacktotop() {
    $backtotop.css({top, right: 0});
  }

  function footerFixBottom() {
    if ($(document.body).height() < windowHeight) {
      $('#footer').addClass('fix-bottom');
    } else {
      $('#footer').removeClass('fix-bottom');
    }
    $('#footer').show();
  }

  $backtotop.click(function () {
    $('html,body').animate({scrollTop: 0}, -1);
    return false;
  });
  $(window).scroll(function () {
    // 移动端不需要"回到顶部"功能
    let ua = navigator.userAgent.toLocaleLowerCase();
    if (ua.includes('iphone') || ua.includes('ipad') || ua.includes('android')) {
      return;
    }
    const windowHeight = $(window).scrollTop();
    if (windowHeight > 200) {
      $backtotop.fadeIn();
    } else {
      $backtotop.fadeOut();
    }
  });

  moveBacktotop();
  footerFixBottom();
  $(window).resize(moveBacktotop);
  $(window).resize(footerFixBottom);


  $('.topic_content a,.reply_content a').attr('target', '_blank');

  // pretty code
  prettyPrint();

  // data-loading-text="提交中"
  $('.submit_btn').click(function () {
    // $(this).button('loading');
  });

  // 广告的统计信息
  $('.sponsor_outlink').click(function () {
    const $this = $(this);
    const label = $this.data('label');
    ga('send', 'event', 'banner', 'click', label, 1.00, {nonInteraction: 1});
  });

  window.Alert = {
    renderAlert: function (data = {}) {
      return [`<div class="myAlert alert fade in ${data.status ? 'alert-' + data.status : ''}">`,
        `<button type="button" class="close" data-dismiss="alert">×</button>`,
        data.title ? `<strong>${data.title}</strong>` : '',
        data.detail ? data.detail : '',
        `</div>`].join('');
    },
    show: function (data, timeout) {
      const $body = $('body');
      const html = this.renderAlert(data);
      $body.append(html);
      if (timeout) {
        setTimeout(() => {
          $body.find(".alert").alert('close');
        }, timeout);
      }
    },
    hide: function () {
      $('body').find(".alert").alert('close');
    }
  }

});
